package com.zcxy360.sandtable.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zcxy360.sandtable.domain.StageUnit;
import com.zcxy360.sandtable.domain.StageUnitMapper;
import com.zcxy360.sandtable.domain.VdrawingMapper;
import com.zcxy360.sandtable.domain.VplanMapper;
import com.zcxy360.sandtable.domain.VproblemMapper;
import com.zcxy360.sandtable.domain.VvideoMapper;
import com.zcxy360.sandtable.util.StringUtil;

@Transactional
@Service
public class StageUnitService {

	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private StageUnitMapper stageUnitMapper;
	@Autowired
	private VvideoMapper vVideoMapper;
	@Autowired
	private VplanMapper vPlanMapper;
	@Autowired
	private VdrawingMapper vDrawingMapper;
	@Autowired
	private VproblemMapper vProblemMapper;

	public StageUnit getByUnitId(Integer unitId) {
		return stageUnitMapper.selectByPrimaryKeyWithCascade(unitId);
	}

	public List<StageUnit> listByStageId(Integer stageId) {
		return stageUnitMapper.listByStageId(stageId);
	}
	
	public Object post(String unitJson) {
		JavaType unitJavaType = objectMapper.getTypeFactory().constructParametricType(List.class, StageUnit.class);
		List<StageUnit> stageUnits = null;
		try {
			stageUnits = objectMapper.readValue(unitJson, unitJavaType);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("解析数据失败");
		} 
		int maxSort = stageUnitMapper.selectMaxSort(stageUnits.get(0).getStageId());
		for(StageUnit stageUnit:stageUnits) {
			stageUnit.setSort(++maxSort);
		}
		stageUnitMapper.create(stageUnits);
		return stageUnits;
	}

	public boolean update(StageUnit stageUnit) {
		String videoIds = stageUnit.getVideoIds();
		String planIds = stageUnit.getPlanIds();
		String drawingIds = stageUnit.getDrawingIds();
		String problemIds = stageUnit.getProblemIds();
		
		if(StringUtil.isNotEmpty(videoIds)) {
			stageUnit.setVvideoIds(vVideoMapper.selectVvideoIds(videoIds));
		}
		if(StringUtil.isNotEmpty(planIds)) {
			stageUnit.setVplanIds(vPlanMapper.selectVplanIds(planIds));
		}
		if(StringUtil.isNotEmpty(drawingIds)) {
			stageUnit.setVdrawingIds(vDrawingMapper.selectVdrawingIds(drawingIds));
		}
		if(StringUtil.isNotEmpty(problemIds)) {
			stageUnit.setVproblemIds(vProblemMapper.selectVproblemIds(problemIds));
		}
		stageUnitMapper.updateByPrimaryKeySelective(stageUnit);
		return true;
	}

	public boolean delete(int[] unitIds) {
		stageUnitMapper.deleteBatch(unitIds);
		return true;
	}

	public boolean sort(Integer unitId1, Integer unitId2) {
		stageUnitMapper.sort(unitId1,unitId2);
		return true;
	}

}
